<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <script>
      //定时器 后台依然会运行
      //requestAnimationFrame
      var num = 0;
      var timer;
      function autoPlay() {
        timer = setInterval(function () {
          num++;
          document.title = num;
        }, 1000);
      }
      autoPlay();
      console.log(timer);
      //浏览器切换后台或者切换回来的时候会触发visibilitychange事件  0级事件不能触发
      // window.onvisibilityChange = function () {
      //   //不能触发
      //   console.log("切换了");
      // };

      //
      //
      var flag = true;
      document.addEventListener("visibilitychange", function () {
        // console.log(111);
        if (flag) {
          console.log("切换走了");
          clearInterval(timer);
        } else {
          console.log("切换回来了");
          autoPlay();
        }
        flag = !flag;
      });
    </script>
  </body>
</html>
